package com.opennews.openplatform.familyexpenseapi.jooq

import com.opennews.openplatform.familyexpenseapi.entity.Tables
import com.opennews.openplatform.familyexpenseapi.entity.tables.records.UserRecord
import org.jooq.RecordContext
import org.springframework.security.crypto.factory.PasswordEncoderFactories

class UserRecordListener : org.jooq.RecordListener {
    override fun insertStart(ctx: RecordContext) {
        // Checks if the record is an instance of UserRecord.
        (ctx.record() as? UserRecord)?.let { record ->
            encodePassword(record)
            record.authFailedAttempt = 0
            record.enabled = true
            record.accountExpired = false
            record.accountLocked = false
            record.passwordExpired = false
        }
    }

    override fun updateStart(ctx: RecordContext) {
        // Checks if the record is an instance of UserRecord.
        (ctx.record() as? UserRecord)?.let { record ->
            if (record.changed(Tables.USER.PASSWORD)) {
                encodePassword(record)
            }
        }
    }

    private fun encodePassword(record: UserRecord) {
        // Apply password encoding logic
        val encodedPassword = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(record.password)
        record.password = encodedPassword
    }
}